#!/usr/bin/python

"""Create netCDF emissions file.

Inputs:
    lon: longitude (float)
    lat: latitude (float)
    flux: Net flux in kg/m2/s (float)
    fluxDate: Date in format YYYYMMDD (int)
    fluxDateSec: Second past 0000hrs UTC (int)
    fileName: netCDF file name (string)
    title: netCDF title global argument (string)
    
Keywords:
    author: Author (string)

    """

__author__  ="Matt Rigby, University of Bristol"
__email__   ="matt.rigby@bristol.ac.uk"

def write_netcdf(lon, lat, flux, fluxDate, fluxDateSec, fileName, title, \
    author=None):

    import sys
    import numpy as np
    import Scientific.IO.NetCDF as nc
    from datetime import date

    timeSize=len(fluxDate)

    if fileName==None:
        print "Specify file name"
        return 0

    if lat[1]<lat[0]:
        print "WRITE_NETCDF ERROR: Latitudes must be in ascending order"
        return 0

    if min(lon)<0.:
        print "WRITE_NETCDF ERROR: Longitudes must not be negative"
        return 0
    
    print "Writing ", fileName

    f=nc.NetCDFFile(fileName, mode='w')
    f.createDimension('time', None)
    f.createDimension('lat', len(lat))
    f.createDimension('lon', len(lon))

    latNC=f.createVariable('lat', 'f', ('lat',))
    lonNC=f.createVariable('lon', 'f', ('lon',))
    dataNC=f.createVariable('flux', 'f', ('time', 'lat', 'lon'))
    dateNC=f.createVariable('date', 'i', ('time', ))
    datesecNC=f.createVariable('datesec', 'i', ('time',))

    latNC.units='degrees_north'
    latNC.long_name='Latitude'
    lonNC.units='degrees_east'
    lonNC.long_name='Longitude'
    dataNC.units='kg/m2/s'
    dataNC.long_name='Net surface flux, monthly mean'
    dateNC.units='YYYYMMDD'
    dateNC.long_name='Date'
    datesecNC.units='seconds after 0000hrs UTC'
    datesecNC.long_name='Time'

    latNC[:]=lat[:].astype('f')
    lonNC[:]=lon[:].astype('f')
    dataNC[:, :, :]=flux.astype('f')
    dateNC[:]=fluxDate
    datesecNC[:]=fluxDateSec

    f.title=title

    if author==None:
        import getpass
        f.author=getpass.getuser()
    else:
        f.author=author

    f.date=str(date.today())
    f.close()

    return 1
